package com.fjut.kms.tools;

import com.fjut.kms.exception.KMSException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
import java.sql.*;

/**
 * Created by Empathy on 2017/7/12.
 */
public class DBTools {
    public  static  String CONN_URL=null;// = "jdbc:mysql://localhost:3306/gpdb";
    public  static  String USERNAME;// ="fzuadmin";
    public  static  String PASS;//="xyz_123A";

    public static Connection getConn(){
        Connection conn = null;
        try{
            //DBTools.getXml();
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(CONN_URL,USERNAME,PASS);
        }
        catch (ClassNotFoundException e){
            e.printStackTrace();
        }
        catch (SQLException e){
            e.printStackTrace();
        }
        return  conn;
    }

    public static void releaseRes(Connection conn, PreparedStatement pstmt, ResultSet rset){
        try{
            if (rset!=null) rset.close();
            if(pstmt!=null) pstmt.close();
            if (conn!=null) conn.close();
        }
        catch (SQLException e){
            e.printStackTrace();
        }
    }

    public static void getXml(){
        try{
            File file=new File("");
            String abspath=file.getAbsolutePath()+"/db.xml";
            file=new File(abspath);
            if(!file.exists()) throw new KMSException("未找到数据库配置文件");
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder documentBuilder = null;
            documentBuilder = dbf.newDocumentBuilder();
            Document document =documentBuilder.parse(file);
            if(document==null) throw new KMSException("配置文件错误！");
            Element statusElt = document.getElementById("status"); // 获取根节点smsReport
            if (statusElt.getNodeValue()!="0")throw new KMSException("配置文件不可用！");
            Element urlElt=document.getElementById("url");
            CONN_URL=urlElt.getNodeValue();
            Element usernameElt=document.getElementById("username");
            USERNAME=usernameElt.getNodeValue();
            Element passElt=document.getElementById("pass");
            PASS=passElt.getNodeValue();
        }catch (Exception ex){
            ex.printStackTrace();
        }

    }
}
